package com.simou.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.simou.common.R;
import com.simou.dto.DishDto;
import com.simou.entity.Category;
import com.simou.entity.Dish;
import com.simou.entity.DishFlavor;
import com.simou.entity.Employee;
import com.simou.service.Impl.CategoryServiceImpl;
import com.simou.service.Impl.DishFlavorServiceImpl;
import com.simou.service.Impl.DishServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    DishServiceImpl dishService;
    @Autowired
    DishFlavorServiceImpl dishFlavorService;
    @Autowired
    CategoryServiceImpl categoryService;
    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/page")
    public R<Page> queryByLimit(int page,int pageSize,String name){
        log.info("page为：{}pageSize为：{}",page,pageSize);

        Page<Dish> pageInfor = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPageInfor = new Page<>(page, pageSize);

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        queryWrapper.orderByAsc(Dish::getUpdateTime);  // 按修改时间降序排序

        dishService.page(pageInfor,queryWrapper);

        // 拷贝pageInfor除了records以外的属性
        BeanUtils.copyProperties(pageInfor,dishDtoPageInfor,"records");
        LambdaQueryWrapper<DishDto> dishDtoLambdaQueryWrapper = new LambdaQueryWrapper<>();

        List<Dish> records = pageInfor.getRecords();
        ArrayList<DishDto> dishDtos = new ArrayList<>();
        for (Dish record : records) {
            DishDto dishDto = new DishDto();
            // dishDto赋值 record 的属性
            BeanUtils.copyProperties(record,dishDto);

            // 根据categoryId查询categoryName
            Long categoryId = record.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category!=null){
                dishDto.setCategoryName(category.getName());
            }

            dishDtos.add(dishDto);
        }
        dishDtoPageInfor.setRecords(dishDtos);

        return R.success(dishDtoPageInfor);
    }

    @PostMapping()
    public R<String> addDishFlavor(@RequestBody DishDto dishDto){
        log.info("dishdto为{}",dishDto);
        // 添加菜品时删除redis缓存，防止显示错误的数据
        String dishKey = "dish_" + dishDto.getCategoryId();
        redisTemplate.delete(dishKey);
        dishService.saveWithFlavor(dishDto);
        return R.success("添加成功");
    }

//    根据id回显菜品信息
    @GetMapping("/{id}")
    public R<DishDto> queryDishById(@PathVariable("id") Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }

    @PutMapping
    public R<String> updateDishById(@RequestBody DishDto dishDto){
        log.info("修改控制器dishDto:{}",dishDto);
        // 更新菜品时删除redis缓存，防止显示错误的数据
        String dishKey = "dish_" + dishDto.getCategoryId();
        redisTemplate.delete(dishKey);

        dishService.updateByIdWithFlavor(dishDto);
        return R.success("修改成功");
    }


//     自定义的路径变量不支持 ${变量}
    @PostMapping("/status/{status}")
    public R<String> changeStatus(@PathVariable("status") Long status,String ids){
        log.info("当前status为{}，菜品id为{}",status,ids);
        String[] idArray = ids.split(",");

        for (String id : idArray) {
            Dish dish = new Dish();
            dish.setId(Long.parseLong(id));
            dish.setStatus(status);
            dishService.updateById(dish);
        }

        return R.success("修改成功");
    }

    @DeleteMapping()
    public R<String> delete(String ids){
        log.info("删除的id为：{}",ids);
        String[] idArray = ids.split(",");

        for (String id : idArray) {
            // 根据id查询categoryId，以清除缓存
            Dish dish = dishService.getById(Long.parseLong(id));
            String dishKey = "dish_" + dish.getCategoryId();
            redisTemplate.delete(dishKey);

            dishService.removeById(Long.parseLong(id));
        }

        return R.success("删除成功");

    }

    @GetMapping("/list")
    public R<List<DishDto>> getById(Long categoryId){
        log.info("category:{}",categoryId);

        // 若redis存在该菜品缓存，直接返回
        String dishKey = "dish_" + categoryId;
        List<DishDto> dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(dishKey);
        if(dishDtos!=null){
            System.out.println("缓存的dishDto:"+dishDtos);
            return R.success(dishDtos);
        }else{
            dishDtos = new ArrayList<>();
        }

        // 根据categoryI查询dish表
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId,categoryId);
        queryWrapper.orderByAsc(Dish::getPrice);
        List<Dish> dishList = dishService.list(queryWrapper);

        for (Dish dish : dishList) {
            // 1.根据categoryId查询categoryName
            Long dishCategoryId = dish.getCategoryId();
            Category category = categoryService.getById(dishCategoryId);

            // 2.根据dishId查询dishFlavor
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);

            DishDto dishDto = new DishDto();
            // 3.将dish + categoryName + dishFlavor 数据整合到dishDto中
            BeanUtils.copyProperties(dish,dishDto);     // dishDto获取dish的数据
            if(category!=null){
                dishDto.setCategoryName(category.getName());    // dishDto获取categoryName
            }
            dishDto.setFlavors(dishFlavorList);     // dishDto获取dishFlavor数据

            dishDtos.add(dishDto);
        }
        // 缓存菜品数据
        redisTemplate.opsForValue().set(dishKey,dishDtos,60, TimeUnit.MINUTES);
        Object o = redisTemplate.opsForValue().get(dishKey);
        System.out.println(o);

        return R.success(dishDtos);
    }

}
